#include "tcp_server.hpp"
#include <iostream>

void TcpServer::Start(const EndPoint& local)
{
    int fd = sock.Create(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
    sock.Bind(local);
    dispatcher.AddConsumer(
        fd,
        EPOLLIN,
        std::bind(&TcpServer::ConnEstabilished, this, std::placeholders::_1)
    );
    sock.Listen();
}

void TcpServer::ConnEstabilished(const Socket& sock)
{
    std::cout << "[Server] conn established" << std::endl;
    sockaddr_in addr;
    int clisock = sock.Accept(addr);        // you can cache clisock to manage it
    if (clisock < 0) return;
    dispatcher.AddConsumer(
        clisock,
        EPOLLIN,
        std::bind(&TcpServer::HandleMessage, this, std::placeholders::_1)
    );
}

void TcpServer::HandleMessage(const Socket& sock)
{
    char msg[200];
    bzero(msg, sizeof msg);
    int cnt = sock.Recv(msg, sizeof msg);
    if (cnt == 0) // client shutdown
    {
        close(sock.GetFd());
        return;
    }
    std::cout << "[Server] Rcvd: " << msg << std::endl;
    strcat(msg, " - response");
    sock.Send(msg, strlen(msg));
    std::cout << "[Server] Sent: " << msg << std::endl;
}
